<!--
 * @Author: zhoulei0232
 * @Date: 2023-04-01 23:06:26
 * @LastEditTime: 2023-04-01 23:06:26
 * @LastEditors: zhoulei0232
 * @Description: 
-->
<!--
 * @Author: zhoulei0232
 * @Date: 2023-04-01 23:03:20
 * @LastEditTime: 2023-04-01 23:05:49
 * @LastEditors: zhoulei0232
 * @Description: 
-->
<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="商品名称" prop="queryGoodsName">
        <el-input
          v-model="queryParams.queryGoodsName"
          placeholder="搜索商品名称"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="画师" prop="queryPainterName">
        <el-input
          v-model="queryParams.queryPainterName"
          placeholder="请选择画师"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['business:goods:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:goods:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:goods:remove']"
          >删除</el-button
        >
      </el-col>
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="pageList"
      @selection-change="handleSelectionChange"
      @sort-change="handleSortChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="100" />
      <el-table-column label="图片" align="center" prop="src">
        <template #default="scope">
          <el-image
            v-if="scope.row.src"
            style="width: 100px; height: 100px"
            :src="uploadShowUrl + scope.row.src"
            :preview-teleported="true"
            :preview-src-list="[uploadShowUrl + scope.row.src]"
            :initial-index="0"
            fit="contain"
          />
          <div v-else style="width: 100px; height: 100px; line-height: 100px">
            未上传图片
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="商品名称"
        align="center"
        prop="goodsName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="画师"
        align="center"
        prop="painterName"
        width="150"
      />
      <el-table-column
        label="价格"
        align="center"
        prop="price"
        width="100"
        sortable
      />
      <el-table-column
        label="库存总量"
        align="center"
        prop="saleSum"
        width="100"
      />
      <el-table-column
        label="已售数量"
        align="center"
        prop="sumOrder"
        width="150"
        sortable
      >
        <template #default="scope">
          <span class="color-blue" @click="handleOpenSub(scope.row)">
            {{ scope.row.sumOrder }}
          </span>
        </template>
      </el-table-column>
      <el-table-column
        label="销售总额"
        align="center"
        prop="sumPrice"
        width="120"
        sortable
      />
      <el-table-column
        label="开售日期"
        align="center"
        prop="saleTime"
        width="150"
        sortable
      >
        <template #default="scope">
          <span>{{ parseTime(scope.row.saleTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="适用范围"
        align="center"
        prop="useRange"
        :show-overflow-tooltip="true"
      >
        <template #default="scope">
          <span>{{ handleChangeUseRange(scope.row.useRange) }}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="200"
      >
        <template #default="scope">
          <el-button
            link
            type="primary"
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:goods:edit']"
            >修改</el-button
          >
          <el-button
            link
            type="primary"
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:goods:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改公告对话框 -->
    <el-dialog :title="title" v-model="open" width="780px" append-to-body>
      <el-form ref="noticeRef" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="画师" prop="painterId">
              <el-select v-model="form.painterId" placeholder="请选择">
                <el-option
                  v-for="dict in painterList"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开售日期" prop="saleTime">
              <el-date-picker
                v-model="form.saleTime"
                type="date"
                placeholder="请输入开始售卖日期"
                format="YYYY/MM/DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="价格" prop="price">
              <el-input-number v-model="form.price" :min="0" :max="9999" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="售卖数量" prop="saleSum">
              <el-input-number v-model="form.saleSum" :min="0" :max="9999" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="适用范围" prop="useRange">
              <el-radio-group v-model="form.useRange">
                <el-radio
                  v-for="dict in useRangeList"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="是否商用" prop="useOtherPlatform">
              <el-radio-group v-model="form.useOtherPlatform">
                <el-radio
                  v-for="dict in useOtherPlatformList"
                  :key="dict.value"
                  :label="dict.value"
                  >{{ dict.label }}</el-radio
                >
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="图片上传" prop="path">
              <el-upload
                class="avatar-uploader"
                :action="uploadUrl"
                :show-file-list="false"
                :before-upload="beforeAvatarUpload"
                :on-success="onSuccessImg"
              >
                <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="debouncedFn">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改公告对话框 -->
    <el-dialog
      :title="detailTitle"
      v-model="openSub"
      width="780px"
      append-to-body
    >
      <el-table v-loading="loadingSub" :data="pageListSub" max-height="600">
        <el-table-column label="序号" align="center" type="index" width="100" />
        <el-table-column
          label="平台"
          align="center"
          prop="platformName"
          width="110"
        />
        <el-table-column
          label="购买人"
          align="center"
          prop="buyUserName"
          width="130"
        />
        <el-table-column
          label="昵称"
          align="center"
          prop="buyNickName"
          width="130"
        />
        <el-table-column
          label="价格"
          align="center"
          prop="salePrice"
          width="60"
        />
        <el-table-column
          label="售卖数量"
          align="center"
          prop="saleSum"
          width="80"
        />

        <el-table-column
          label="购买日期"
          align="center"
          prop="createTime"
          width="100"
        >
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d}") }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup name="Goods">
import {
  listGoods,
  addGoods,
  updateGoods,
  deleteGoods,
} from "@/api/business/goods";
import { listPainter } from "@/api/business/painter";
import { listAllOrder } from "@/api/business/order";
import { useDebounceFn } from "@vueuse/core";

const { proxy } = getCurrentInstance();
// 图片上传地址
const uploadUrl = import.meta.env.VITE_APP_UPLOAD_API + "api/uploadCos/goods";
const uploadShowUrl = import.meta.env.VITE_APP_COS_API;
const imageUrl = ref("");

const pageList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const detailTitle = ref(""); // 详情标题栏

const painterList = ref([]); // 画师下拉框
const useOtherPlatformList = ref([
  { label: "是", value: "是" },
  { label: "否", value: "否" },
]);

const useRangeList = ref([
  { label: "仅文游圈作者用", value: 1 },
  { label: "仅文游圈、小说、广播短剧作者用", value: 2 },
  { label: "全网可商用", value: 3 },
]);
const openSub = ref(false); // 查看购买详情
const loadingSub = ref(false);
const pageListSub = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    queryGoodsName: undefined,
    queryPainterName: undefined,
    orderType: undefined,
    orderName: undefined,
  },
  rules: {
    name: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
    painterId: [{ required: true, message: "画师不能为空", trigger: "change" }],
    saleTime: [
      { required: true, message: "售卖日期不能为空", trigger: "change" },
    ],
  },
});

const { queryParams, form, rules } = toRefs(data);

const beforeAvatarUpload = (rawFile) => {
  if (rawFile.type !== "image/png" && rawFile.type !== "image/jpeg") {
    ElMessage.error("Avatar picture must be PNG format!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("Avatar picture size can not exceed 2MB!");
    return false;
  }
  return true;
};
function onSuccessImg(response) {
  if (response.code == 200) {
    form.value.src = response.data;
    imageUrl.value = uploadShowUrl + response.data;
  }
}
/** 查询画师列表 */
function getPainterList() {
  // loading.value = true;
  listPainter().then((response) => {
    painterList.value = response.data.map((item) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
    // loading.value = false;
  });
}

/** 查询公告列表 */
function getList() {
  loading.value = true;
  listGoods(queryParams.value).then((response) => {
    pageList.value = response.data.rows;
    total.value = response.data.count;
    loading.value = false;
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}
/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    painterId: undefined,
    saleTime: undefined,
    price: 0,
    saleSum: 0,
    useRange: 1,
    src: "",
    useOtherPlatform: "是",
  };
  imageUrl.value = null;
  proxy.resetForm("noticeRef");
}
/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}
/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.orderType = undefined;
  queryParams.value.orderName = undefined;
  handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "新增";
}
/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  if (!row.id) {
    let arr = pageList.value.filter((item) => {
      return item.id == ids.value;
    });
    form.value = {
      ...arr[0],
      name: arr[0].goodsName,
    };
  } else {
    form.value = {
      ...row,
      name: row.goodsName,
    };
    imageUrl.value = uploadShowUrl + row.src;
  }

  open.value = true;
  title.value = "修改";
}
// 防抖操作
const debouncedFn = useDebounceFn(
  () => {
    submitForm();
  },
  1000,
  { maxWait: 3000 }
);

/** 提交按钮 */
function submitForm() {
  proxy.$refs["noticeRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != undefined) {
        updateGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addGoods(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}
/** 删除按钮操作 */
function handleDelete(row) {
  let deleteId = row.id || ids.value;
  if (!Array.isArray(deleteId)) {
    deleteId = [deleteId];
  }
  let arrList = pageList.value.filter((item) => {
    return;
  });
  proxy.$modal
    .confirm('是否确认删除公告编号为"' + deleteId + '"的数据项？')
    .then(function () {
      return deleteGoods({ id: deleteId });
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 查看购买详情 */
function handleOpenSub(row) {
  openSub.value = true;
  loadingSub.value = true;
  listAllOrder({ goodsId: row.id }).then((response) => {
    pageListSub.value = response.data;
    detailTitle.value =
      "购买详情: " +
      row.goodsName +
      " - " +
      row.painterName +
      " - " +
      response.data.length +
      "份";
    loadingSub.value = false;
  });
}

function handleChangeUseRange(params) {
  let arr = useRangeList.value.filter((item) => {
    return item.value == params;
  });
  if (arr && arr.length > 0) {
    return arr[0].label;
  } else {
    return " ";
  }
}
// 排序
function handleSortChange(column) {
  let data1;
  if (column.order == "ascending") {
    data1 = "ASC";
  } else if (column.order == "descending") {
    data1 = "DESC";
  }
  if (!data1) {
    data.queryParams.orderName = undefined;
  } else {
    data.queryParams.orderName = column.prop;
  }
  data.queryParams.orderType = data1;
  getList();
}
getList();
getPainterList();
</script>
<style lang="scss" scoped>
.color-blue {
  color: rgb(0, 119, 255);
  cursor: pointer;
}
.avatar-uploader {
  width: 200px;
  height: 300px;
  .avatar {
    width: 100%;
    height: 100%;
  }
}
.avatar-uploader :deep(.el-upload) {
  width: 100%;
  height: 100%;
  border: 1px dashed #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader :deep(.el-upload:hover) {
  border-color: #409eff;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
